package com.itheima.netty.selector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: pzj
 * \* Date: 2021/12/3
 * \* Time: 15:08
 * \* Description:
 * \
 */
public class WriteServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);

        Selector selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT);

        ssc.bind(new InetSocketAddress(8080));
        while (true){
            selector.select();
            final Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isAcceptable()){
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    SelectionKey sckey = sc.register(selector, 0, null);
                    sckey.interestOps(SelectionKey.OP_READ);

                    //1、向客户端发送大量数据
                    StringBuilder stringBuilder= new StringBuilder();
                    for (int i =0;i<10000000;i++){
                        stringBuilder.append("a");
                    }
                    ByteBuffer buffer = Charset.defaultCharset().encode(stringBuilder.toString());
                    //2、返回值代表实际写入的字节数
                    int write = sc.write(buffer);
                    System.out.println(write);

                    //3、判断是否有剩余内容
                    if (buffer.hasRemaining()){
                        //4、关注可写事件
                        sckey.interestOps(sckey.interestOps()+SelectionKey.OP_WRITE);
                        //5、把未写完的数据挂到key上
                        sckey.attach(buffer);
                    }
                }else if (key.isWritable()){
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    SocketChannel sc = (SocketChannel) key.channel();
                    int write = sc.write(buffer);
                    System.out.println(write);
                    //6、清理操作
                    if (!buffer.hasRemaining()){
                        key.attach(null);//清楚buffer附件
                        key.interestOps(key.interestOps()-SelectionKey.OP_WRITE);//不需要关注可写事件
                    }
                }
            }
        }
    }
}